<template>
  <div class="child-component">
    <h2>子组件：事件通信</h2>
    
    <div class="counter">
      <h3>计数器：{{ count }}</h3>
      <div class="buttons">
        <button @click="increment">增加</button>
        <button @click="decrement">减少</button>
        <button @click="reset">重置</button>
      </div>
    </div>

    <div class="message-input">
      <input 
        v-model="message" 
        placeholder="输入消息" 
        @input="sendMessage"
      >
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 定义可触发的事件
const emit = defineEmits([
  'count-change',    // 计数变化事件
  'reset-count',     // 重置计数事件
  'send-message'     // 发送消息事件
])

// 计数器状态
const count = ref(0)
const message = ref('')

// 增加计数
const increment = () => {
  count.value++
  // 触发计数变化事件，传递当前计数
  emit('count-change', count.value)
}

// 减少计数
const decrement = () => {
  if (count.value > 0) {
    count.value--
    // 触发计数变化事件，传递当前计数
    emit('count-change', count.value)
  }
}

// 重置计数
const reset = () => {
  count.value = 0
  // 触发重置事件
  emit('reset-count')
}

// 发送消息
const sendMessage = () => {
  // 触发发送消息事件，传递输入的消息
  emit('send-message', message.value)
}
</script>

<style scoped>
.child-component {
  background-color: #f4f4f4;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.counter {
  margin-bottom: 20px;
}

.buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

.message-input {
  margin-top: 20px;
}

input {
  padding: 10px;
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
